package com.aiti.lulian.service.newCard;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.newCard.CardTemplateStyleFieldBo;
import com.aiti.lulian.entity.newCard.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;

import java.util.*;

/**
 * description:
 * auth fcb
 * date 2025-09-11 14:02
 **/
@Slf4j
@Data
public class ImportExcelCardDataRowHandler implements RowHandler {

    private List<CardBaseInfo> cardBaseInfoList;

    private List<CardStyleFieldData> cardStyleFieldDataList;

    private List<CardComponentData> cardComponentDataList;

    private List<CardAudit> cardAuditList;

    private List<CardTemplateStyleFieldBo> cardTemplateStyleFields;
    // 字段索引
    private Map<Integer,CardTemplateStyleFieldBo> fielsdIndexMap;
    // 固定属性值对应的索引。姓名、公司、职位、手机、邮箱
    private Map<String, Integer> fixFieldIndexMap;
    private List<String> fixFieldNameList = Arrays.asList("姓名", "公司", "职位", "手机", "邮箱");

    private Boolean success;

    private String errorMsg;

    private String enterpriseId;
    private String templateId;
    // 创建人，一般是管理员
    private String userId;
    private String enterpriseVersion;
    private Date expireTime;

    // 模板组件数据，用于创建名片组件数据
    private List<CardEnterpriseComponent> templateComponentList;
    // 用于判断导入的手机号是否重复
    private List<String> mobileSet;

    public ImportExcelCardDataRowHandler(List<CardTemplateStyleFieldBo> cardTemplateStyleFields, List<CardEnterpriseComponent> templateComponentList, String userId, String enterpriseId, String templateId, String enterpriseVersion, Date expireTime) {
        this.cardAuditList = new ArrayList<>(200);
        this.cardBaseInfoList = new ArrayList<>(200);
        this.cardStyleFieldDataList = new ArrayList<>(200);
        this.cardComponentDataList = new ArrayList<>(200);
        this.cardTemplateStyleFields = cardTemplateStyleFields;
        this.success = true;
        this.fielsdIndexMap = new java.util.HashMap<>(20);
        this.fixFieldIndexMap = new java.util.HashMap<>(10);
        this.userId = userId;
        this.enterpriseVersion = enterpriseVersion;
        this.expireTime = expireTime;
        this.templateComponentList = templateComponentList;
        this.enterpriseId = enterpriseId;
        this.templateId = templateId;
        this.mobileSet = new ArrayList<>();
    }

    /**
     * 处理一行数据
     *
     * @param sheetIndex 当前Sheet序号
     * @param rowIndex   当前行号，从0开始计数
     * @param rowCells   行数据，每个Object表示一个单元格的值
     */
    @Override
    public void handle(int sheetIndex, long rowIndex, List<Object> rowCells) {
        if(sheetIndex != 0 || !success) {
            return;
        }
        if(rowIndex > 502) {
            this.success = false;
            this.errorMsg = "超出最大行数";
            return;
        }
        // 处理第三行的表头，确定顺序
        if(rowIndex == 2) {
            for(int i = 0; i < cardTemplateStyleFields.size(); i++) {
                String excelFieldName = (String)rowCells.get(i);
                CardTemplateStyleFieldBo templateField = this.findField(excelFieldName);
                if(templateField == null) {
                    this.success = false;
                    this.errorMsg = "第" + (rowIndex + 1) + "行，第" + (i + 1) + "列，字段名称错误：" + excelFieldName;
                    return;
                }
                if(fixFieldNameList.contains(templateField.getBaseName())) {
                    this.fixFieldIndexMap.put(templateField.getBaseName(), i);
                }
                this.fielsdIndexMap.put(i, templateField);
            }
        }else if(rowIndex >= 3){
            // 判断必填项是否填写
            this.checkRequiredField(rowCells, rowIndex);
            if(!success) {
                return;
            }
            // 读取并构建名片相关数据
            CardBaseInfo cardBaseInfo = this.buildCardBaseInfo(rowCells);
            this.cardBaseInfoList.add(cardBaseInfo);
            if(mobileSet.contains(cardBaseInfo.getEnterpriseMobile())) {
                this.success = false;
                this.errorMsg = "第" + (rowIndex + 1) + "行，手机号重复：" + cardBaseInfo.getEnterpriseMobile();
                return;
            }else {
                if(StrUtil.isNotBlank(cardBaseInfo.getEnterpriseMobile())) {
                    mobileSet.add(cardBaseInfo.getEnterpriseMobile());
                }
            }
            // 卡片字段数据
            this.buildCardStyleFieldData(cardBaseInfo.getBaseId(), rowCells);
            // 卡片组件数据
            this.createCardComponentData(templateComponentList, cardBaseInfo.getBaseId());
            // 添加待审核列表
            this.addToAuditList(cardBaseInfo.getBaseId(), enterpriseId, templateId);
        }
        //log.info("处理行数据：sheetIndex=" + sheetIndex + ", rowIndex=" + rowIndex + ", rowCells=" + rowCells);
    }

    private void checkRequiredField(List<Object> rowCells, long rowIndex) {
        this.fielsdIndexMap.forEach((index, field) -> {
            if(field.getRequiredFlag()) {
                String value = Convert.convert(String.class, rowCells.get(index));
                if(StrUtil.isBlank( value)) {
                    this.success = false;
                    this.errorMsg = "第" + (rowIndex + 1) + "行，第" + (index + 1) + "列，字段不能为空：" + field.getBaseName();
                }
            }
        });
    }

    private void addToAuditList(String cardId, String enterpriseId, String templateId) {
        CardAudit cardAudit = new CardAudit();
        cardAudit.setBaseId(IdUtil.simpleUUID());
        cardAudit.setEnterpriseId(enterpriseId);
        cardAudit.setTemplateId(templateId);
        cardAudit.setCardId(cardId);
        cardAudit.setCardStatus(NewCardBusinessConstant.CARD_STATUS_1);
        cardAudit.setBaseCreateBy(userId);
        cardAudit.setBaseUpdateBy(userId);
        cardAudit.setBaseCreateTime(new Date());
        cardAudit.setBaseUpdateTime(new Date());
        this.cardAuditList.add(cardAudit);
    }

    public void createCardComponentData(List<CardEnterpriseComponent> templateComponentData, String cardId) {
        if (CollectionUtil.isEmpty(templateComponentData)) {
            return;
        }
        for (CardEnterpriseComponent templateComponent : templateComponentData) {
            CardComponentData componentData = new CardComponentData();
            componentData.setBaseId(IdUtil.simpleUUID());
            componentData.setCardId(cardId);
            componentData.setTemplateComponentId(templateComponent.getBaseId());
            componentData.setComponentMetaData(templateComponent.getComponentMetaData());
            componentData.setSort(templateComponent.getSort());

            this.cardComponentDataList.add(componentData);
        }
    }

    private void buildCardStyleFieldData(String cardId, List<Object> rowCells) {
        for(int i = 0; i < cardTemplateStyleFields.size(); i++) {
            String excelValue = Convert.convert(String.class, rowCells.get(i));
            CardTemplateStyleFieldBo cardTemplateStyleFieldBo = fielsdIndexMap.get(i);
            CardStyleFieldData cardStyleFieldData = new CardStyleFieldData();
            cardStyleFieldData.setBaseId(IdUtil.simpleUUID());
            cardStyleFieldData.setCardId(cardId);
            cardStyleFieldData.setStyleFieldId(cardTemplateStyleFieldBo.getBaseId());
            cardStyleFieldData.setStyleFieldValue(excelValue);
            this.cardStyleFieldDataList.add(cardStyleFieldData);
        }
    }

    private CardBaseInfo buildCardBaseInfo(List<Object> rowCells) {
        CardBaseInfo cardBaseInfo = new CardBaseInfo();
        cardBaseInfo.setBaseId(IdUtil.simpleUUID());
        if(fixFieldIndexMap.containsKey("姓名")) {
            cardBaseInfo.setName(Convert.convert(String.class, rowCells.get(fixFieldIndexMap.get("姓名"))));
        }else {
            cardBaseInfo.setName("");
        }
        if(fixFieldIndexMap.containsKey("公司")) {
            cardBaseInfo.setEnterpriseName(Convert.convert(String.class, rowCells.get(fixFieldIndexMap.get("公司"))));
        }else {
            cardBaseInfo.setEnterpriseName("");
        }
        if(fixFieldIndexMap.containsKey("职位")) {
            cardBaseInfo.setPositionOne(Convert.convert(String.class, rowCells.get(fixFieldIndexMap.get("职位"))));
        }else {
            cardBaseInfo.setPositionOne("");
        }
        if(fixFieldIndexMap.containsKey("手机")) {
            cardBaseInfo.setEnterpriseMobile(Convert.convert(String.class, rowCells.get(fixFieldIndexMap.get("手机"))));
        }else {
            cardBaseInfo.setEnterpriseMobile("");
        }
        if(fixFieldIndexMap.containsKey("邮箱")) {
            cardBaseInfo.setEnterpriseEmail(Convert.convert(String.class, rowCells.get(fixFieldIndexMap.get("邮箱"))));
        }else {
            cardBaseInfo.setEnterpriseEmail("");
        }
        cardBaseInfo.setCardVersion(enterpriseVersion);
        cardBaseInfo.setExpireTime(expireTime);
        cardBaseInfo.setUseResourceType(NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_3);
        cardBaseInfo.setBaseCreateBy(userId);
        cardBaseInfo.setBaseCreateTime(new Date());
        cardBaseInfo.setBaseUpdateBy(userId);
        cardBaseInfo.setBaseUpdateTime(new Date());
        cardBaseInfo.setIsDelete(0);
        return cardBaseInfo;
    }

    private CardTemplateStyleFieldBo findField(String fieldName) {
        for(CardTemplateStyleFieldBo cardTemplateStyleFieldBo : cardTemplateStyleFields) {
            if(fieldName.equals(cardTemplateStyleFieldBo.getBaseName())) {
                return cardTemplateStyleFieldBo;
            }else {
                if(fieldName.equals(cardTemplateStyleFieldBo.getBaseName() + "（必填）")) {
                    return cardTemplateStyleFieldBo;
                }
            }
        }
        return null;
    }

    /**
     * 处理一个单元格的数据
     *
     * @param sheetIndex    当前Sheet序号
     * @param rowIndex      当前行号
     * @param cellIndex     当前列号
     * @param value         单元格的值
     * @param xssfCellStyle 单元格样式
     */
    @Override
    public void handleCell(int sheetIndex, long rowIndex, int cellIndex, Object value, CellStyle xssfCellStyle) {

    }

    /**
     * 处理一个sheet页完成的操作
     */
    @Override
    public void doAfterAllAnalysed() {

    }

}
